<?php
use Modules\Category\Models\Category;
use Illuminate\Support\Facades\Log;

if (!function_exists('cat_success')) {
    function cat_success($data = [], $msg = '操作成功', $code = 200) {
        return response()->json(['status'=>true,'message'=>$msg,'data'=>$data], $code);
    }
}

if (!function_exists('cat_error')) {
    function cat_error($msg = '操作失败', $code = 400, $data = []) {
        return response()->json(['status'=>false,'message'=>$msg,'data'=>$data], $code);
    }
}

if (!function_exists('categoryTree')) {
    function categoryTree($status = null, $pid = 0)
    {
        $tree = [];
        foreach (Category::select(['id','name','pid','level','status'])->where('pid', $pid)->orderBy('id')->get() as $cat) {
            $children = categoryTree($status, $cat->id);
            if ($status === null || $cat->status == $status || $children) {
                $item = $cat->toArray();
                $item['children'] = $children;
                $tree[] = $item;
            }
        }
        return $tree;
    }
}
//没被禁用
if(!function_exists('cache_category')){
    function cache_category(){
        cache()->rememberForever('category_tree', function () {
            return categoryTree(1);
        });
    }
}
//全部
if(!function_exists('cache_category_all')){
    function cache_category_all(){
        return cache()->rememberForever('category_tree_all', function () {
            return categoryTree();
        });
    }
}


if(!function_exists('clear_cache_category')){
    function clear_cache_category(){
        cache()->forget('category_tree');
        cache()->forget('category_tree_all');
        };
    }
